package com.spark.data

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.helper.DatePickerDiaFragment
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.data.model.CrewListModel
import com.spark.data.model.FileListModel
import com.spark.data.model.ReqFileResModel
import kotlinx.android.synthetic.main.frag_file_transfer.*

/**
 * transfer some file to s.b
 */
class FileTransferFragment : BaseFragment() {
    private val req_select_crew = 0x111
    private val req_select_file = 0x222

    private val crews: MutableList<CrewListModel.ResultMap> = mutableListOf()
    private var files: MutableList<FileListModel.ResultMap.File> = mutableListOf()

    companion object {
        fun newInstance(): FileTransferFragment {
            val target = FileTransferFragment()
            val args = Bundle()
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_file_transfer
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        iv_back.setOnClickListener { activity?.finish() }

        tv_time.setOnClickListener {
            val datePickerDialog = DatePickerDiaFragment.newInstance()
            datePickerDialog.show(childFragmentManager, "date")
            datePickerDialog.setOnDateTapedListener {
                tv_time.text = sdf("yyyy-MM-dd hh:mm").format(it)
            }
        }
        /**
         * the target u want to transfer file
         */
        ll_to.setOnClickListener {
            startForResult(CrewsFragment.newInstance(), req_select_crew)
        }

        ll_target_file.setOnClickListener {
            startForResult(FilesFragment.newInstance(), req_select_file)
        }
        /**
         * submit
         */
        tv_submit.setOnClickListener {
            val remark = et_remark.text.toString().trim()
            requestFiles(remark)
        }
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        super.onFragmentResult(requestCode, resultCode, data)
        val gson = Gson()
        when (requestCode) {
            req_select_crew -> {
                if (resultCode == CrewsFragment.res_crew) {
                    val type = object : TypeToken<MutableList<CrewListModel.ResultMap>>() {}.type
                    val crewlist = data?.getString("crew")?.let {
                        LogUtils.e(it)
                        if (it.isNullOrBlank()) return@let null
                        return@let gson.fromJson<MutableList<CrewListModel.ResultMap>>(it, type)
                    }
                    this.crews.clear()
                    crewlist?.let { this.crews.addAll(it) }
                    LogUtils.e(crews.toString())
                }
            }
            req_select_file -> {
                if (resultCode == FilesFragment.res_files) {
                    val type = object : TypeToken<MutableList<FileListModel.ResultMap.File>>() {}.type
                    val filelist = data?.getString("files")?.let {
                        LogUtils.e(it)
                        if (it.isNullOrBlank()) return@let null
                        return@let gson.fromJson<MutableList<FileListModel.ResultMap.File>>(it, type)
                    }
                    this.files.clear()
                    filelist?.let { files.addAll(it) }
                    LogUtils.e(files.toString())
                }
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun requestFiles(remark: String = "") {
        if (files.isEmpty()) {
            alert("请选择文件")
            return
        }
        if (crews.isEmpty()) {
            alert("请选择传送人")
            return
        }
        val fileIds = mutableListOf<String>()
        files.forEach { fileIds.add(it.id.toString()) }
        val crewIds = mutableListOf<String>()
        crews.forEach { crewIds.add(it.employeeno) }

        val params = mutableMapOf(
                Const.qr_accept_file_userid to crewIds.append(","),
                Const.qr_fileId to fileIds.append(","),
                Const.qr_remark to remark
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_request_files}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ReqFileResModel::class.java)?.apply {
                                if (code == "200") {
                                    pop()
                                } else {
                                    error(msg)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }
}